package dao.impl;

import dao.UserDao;
import pojo.User;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    public List<User> findAll(){
        //jdbc 操作


        List<User> users=new ArrayList<>();

        //jdbc操作数据库 查询
        try {
            //1、加载驱动
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            }
            //2、获取链接
            String url = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";

            try {
                Connection connection = DriverManager.getConnection(url, "root", "123456");
                //if(connection!=null)
                //   {
                //     System.out.println("连接成功");
                //    }
                //3、写sql
                String sql = "select * from user";

                //4、预编译sql
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                //5、有参数设置参数
                //6、执行sql
                ResultSet resultSet = preparedStatement.executeQuery();
                //7、遍历结果集
                while (resultSet.next()) {
                    User user = new User();//创建新对象user
                    user.setId(resultSet.getInt(1));
                    user.setName(resultSet.getString(2));
                    user.setPass(resultSet.getString(3));
                    //将对象添加到集合中
                    users.add(user);
                }
                resultSet.close();
                preparedStatement.close();
                connection.close();
                return users;
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }

        } catch (RuntimeException e) {
            throw new RuntimeException(e);
        }
    }

}
